package com.timkj.zgyd.wxPay;

import com.github.wxpay.sdk.WXPayUtil;
import com.timkj.zgyd.dao.ZgydOrderDao;
import com.timkj.zgyd.dao.ZgydUserDao;
import com.timkj.zgyd.entity.Zgyd_User_tb;
import com.timkj.zgyd.entity.Zgyd_order_tb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author : liji
 * @date : 2020-09-04 09:44
 */
@Slf4j
@Component
public class WxPayService {
    private ZgydOrderDao zgydOrderDao;
    private ZgydUserDao zgydUserDao;

    @Autowired
    public WxPayService(ZgydOrderDao zgydOrderDao, ZgydUserDao zgydUserDao) {
        this.zgydOrderDao = zgydOrderDao;
        this.zgydUserDao = zgydUserDao;
    }

    /**
     * 统一下单
     */
    public Map<String,String> payH5(String total_fee, String ip, String openid, String xtddh, HttpServletRequest request){
        // 封装需要的信息ip
        String xmlResult = null;
        try {
            // 1. 拼接下单地址参数
            Map<String,String> param = new HashMap<>();
            param.put("appid", PayConfig.APP_ID); // 公总号ID
            param.put("mch_id", PayConfig.MCH_ID); // 商户号ID
            param.put("nonce_str", WXPayUtil.generateNonceStr());  // 随机字符串
            param.put("body", "中国移动校园卡 \n订单号: " + xtddh) ;// 商品描述
            param.put("out_trade_no",xtddh ); // 商户订单号
            String total_fee1 = "5000";
            param.put("total_fee", total_fee1);//金额（分）
            param.put("spbill_create_ip", ip); // 商户终端ip
            param.put("notify_url", "http://81.70.13.128:10011/zgyd/order/getWxInform"); // H5微信异步通知回调地址
            param.put("trade_type", "JSAPI"); // H5支付类型
            param.put("openid",openid );
            String scene_info = "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":"+PayConfig.WAP_URL+",\"wap_name\": \"中国移动校园卡\"}}";
            param.put("scene_info", scene_info); // 需要支付的场景信息;有几种方式,参考文档
            // 生成签名,官方默认MD5+商户秘钥+参数信息
            String sign = WXPayUtil.generateSignature(param, PayConfig.API_KEY);
            param.put("sign", sign);

            // 将所有参数转换为xml形式
            String xmlParam = WXPayUtil.mapToXml(param);
            // 2. 发送请求
            //String xmlStr = HttpRequest.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"
            HttpClient httpClient = new HttpClient(PayConfig.UFDODER_URL);
            httpClient.setHttps(true);// https协议
            httpClient.setXmlParam(xmlParam);
            httpClient.post();
            request.getSession().setAttribute("zgyd_order_bh",xtddh);
            // 获取结果
            xmlResult = httpClient.getContent();
            assert xmlResult != null;
            //商户订单号写入表里
            Zgyd_User_tb zgyd_user_tb = new Zgyd_User_tb();
            zgyd_user_tb.setZgyd_user_wxOpenid(openid);
            zgyd_user_tb.setZgyd_user_order_shbh(xtddh);
            zgydUserDao.UpdateUserOrderShbh(zgyd_user_tb);
            Map<String,String> map = WXPayUtil.xmlToMap(xmlResult);
            //签名 和 订单金额
            Zgyd_order_tb orderTb = new Zgyd_order_tb();
            orderTb.setZgyd_order_bh(xtddh);
            orderTb.setZgyd_order_sign(sign);
            orderTb.setZgyd_order_total_fee(total_fee1);
            zgydOrderDao.UpdateOrderSign(orderTb);
            zgydOrderDao.UpdateOrderTotalFee(orderTb);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成商户订单号
     */
    public static String generateOrderSN() {
        return System.currentTimeMillis() +
                generateShortUUID();
    }

    private static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };

    private static String generateShortUUID() {
        StringBuilder shortBuffer = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

}
